package com.bjsxt.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import org.apache.shiro.subject.Subject;
import javax.servlet.http.HttpSession;

import java.util.Enumeration;

@Controller
public class MyController {
    //声明单元方法：跳转登录页面
    @RequestMapping("login")
    public String loginPage(){
        return "login";
    }
    //声明单元方法：跳转主页面
    @RequestMapping("main")
    public String getMainPage(){
        return "main";
    }
    //声明单元方法：获取session中的数据
    @RequestMapping("demosession")
    @ResponseBody
    public String demoSession(HttpSession session){
        //遍历session中的数据
        Enumeration<String> names=session.getAttributeNames();
        while (names.hasMoreElements()){
            String name = names.nextElement();
            Object value = session.getAttribute(name);
            //打印结果
            System.out.println(name+"====="+value);
        }
        return "session";
    }
    //声明单元方法：用户登录
    @RequestMapping("userLogin")
    public String userLogin(String uname, String pwd, @RequestParam(defaultValue = "false") Boolean remember){
    //获取subject对象
        Subject subject= SecurityUtils.getSubject();
    //创建对象存储认证信息
        AuthenticationToken token = new UsernamePasswordToken(uname,pwd,remember);
    //调用shiro的login方法完成登录认证
        try {
            //login（）方法没有返回值，只能通过是否有异常判断是否登录成功
            subject.login(token);
            return "redirect:/main";
        }catch (UnknownAccountException e){
            System.out.println("账号不存在");
            return "redirect:/login";
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
            return "redirect:/login";
        }catch (ExcessiveAttemptsException e){
            return "redirect:/login";
        }
    }


}
